package 链表;

import java.util.List;

// https://leetcode-cn.com/problems/remove-linked-list-elements/
public class _203_移除链表元素 {
    // 1. 递归
    public static ListNode removeElements1(ListNode head, int val) {
        if (head == null) return head;
        ListNode node = removeElements1(head.next, val);
        if (head.val == val) {
            return node;
        } else {
            head.next = node;
            return head;
        }
    }

    public static ListNode removeElements2(ListNode head, int val) {
        if (head == null) return head;
        ListNode dynamicNode = new ListNode(-1);
        dynamicNode.next = head;
        head = dynamicNode;
        while (head != null) {
            ListNode next = head.next;
            if (next == null) break;
            if (next.val == val) {
                head.next = next.next;
            } else {
                head = head.next;
            }
        }

        return dynamicNode.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(6);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);
        System.out.println(head);
        head = removeElements2(head, 6);
        System.out.println(head);
    }
}
